<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\pay;

use support\Container;
use app\common\model\OrderMaster;
use app\common\model\ChannelAccount;

class PayService
{
    // 实例化支付网关
    public function invoke($code)
    {
        $class = "\\app\\api\\collection\\{$code}";

        if (!class_exists($class)) {
            throw new \Exception("Class {$class} does not exist");
        }

        return Container::get($class);
    }

    // 加载订单
    public function loadOrder($trade_no)
    {
        if (empty($trade_no)) {
            throw new \Exception("订单号为空!");
        }

        $order_master = OrderMaster::where("trade_no", $trade_no)->find();

        if (!$order_master) {
            throw new \Exception("不存在该订单号!");
        }
        $order = $order_master->loadModel;
        if (!$order) {
            throw new \Exception("不存在该订单!");
        }
        $channel = $order->channel;
        if (!$channel) {
            throw new \Exception("不存在该支付网关!");
        }
        $account = $order->channelAccount;
        if (!$account) {
            throw new \Exception("不存在支付网关：{$channel->title}的账号!");
        }

        return $order;
    }

    // 支付
    public function pay($order, $trade_no, $total_price)
    {

        if ($order->channelAccount->status !== 1) {
            return json('该支付网关账号已关闭！');
        }
        $channel = $this->invoke($order->channel->code);
        // 对应的支付网关的支付方法
        return $channel->pay($order->trade_no, $order->goods_name, $total_price);
    }

    // 回调
    public function notify($request, $account_id)
    {
        if (isset($request['data'])) {
            $request = json_decode($request['data'], true);
        }
        try {
            if (isset($request['out_trade_no'])) {
                $order   = $this->loadOrder($request['out_trade_no']);
                $channel = $this->invoke($order->channel->code);
            } else if (!empty($account_id)) {
                // 通过网关查找 网关码
                $account = ChannelAccount::where('status', 1)->findOrFail($account_id);
                $channel = $this->invoke($account->channel->code);
            } else {
                throw new \Exception("缺少参数!");
            }
            // 对应的支付网关的支付方法
            return $channel->notify($request, $account_id);
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

}
